package zut.edu.cs.network.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.PreparedStatement;

public class DBUtil {
//	加载驱动
	private final static String DRIVER_CLASS = "com.mysql.jdbc.Driver";
	
//	设置账号密码
	private final static String URL = "jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf-8";
	private final static String USERNAME = "root";
	private final static String PASSWORD = "root";
	
//	属性对象
//	private static ComboPooledDataSource dataSource;
	private static Connection connection;
	private static PreparedStatement preparedStatement;
	private static ResultSet resultSet;
	
	static {
		try {
			Class.forName(DRIVER_CLASS);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
//	获得连接
	public static Connection getConnection() throws SQLException {
		connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		
		/*dataSource = new ComboPooledDataSource();
		connection = dataSource.getConnection();*/
		return connection;
	}
	
//	释放
	public static void close() throws SQLException {
		if (resultSet != null) {
			resultSet.close();
		}
		if (preparedStatement != null) {
			preparedStatement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}
	
//	插入，更改，删除
	public static int insert(String sql,Object[] object) throws SQLException { 
//		获得连接
		connection = getConnection();
//		准备sql
		preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
//		填充sql中的 ?
		for (int i = 0; i < object.length; i++) {
			preparedStatement.setObject(i+1, object[i]);
		}
//		执行sql 被返回记录数
		return preparedStatement.executeUpdate();
	}
	
//	查询
	public static ResultSet query(String sql,Object...object) throws SQLException { 
		connection = getConnection();
		
		preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
		
		for (int i = 0; i < object.length; i++) {
			preparedStatement.setObject(i+1, object[i]);
		}
		resultSet = preparedStatement.executeQuery();
		return resultSet;
	}

}
